package com.feng.usercenter.controller;


import com.feng.usercenter.common.BaseResult;
import com.feng.usercenter.common.ErrorCode;
import com.feng.usercenter.common.ResultUtils;
import com.feng.usercenter.constant.BaseConst;
import com.feng.usercenter.exception.BusinessException;
import com.feng.usercenter.model.User;
import com.feng.usercenter.model.request.UserLoginRequest;
import com.feng.usercenter.model.request.UserRegisterRequest;
import com.feng.usercenter.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = {"http://localhost:8081/"}, allowCredentials = "true")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户登录
     * @param userLoginRequest 登录体
     * @param request 请求
     * @return 用户信息（脱敏）
     */
    @PostMapping("/login")
    public BaseResult<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null){
            throw new BusinessException(ErrorCode.NULL_ERROR, "请求数据为空");
        }

        // 基础校验（与业务无关）
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();

        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "账户或密码为空！");
        }

        User user =  userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResult<Integer> userLogout(HttpServletRequest request) {
        if (request == null){
            throw new BusinessException(ErrorCode.NULL_ERROR, "请求为空！");
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }


    /**
     * 用户注册
     * @param userRegisterRequest 注册体
     * @return 用户id
     */
    @PostMapping("/register")
    public BaseResult<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 基础校验（与业务无关）
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();

        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        long result = userService.userRegister(userAccount, userPassword, checkPassword, planetCode);
        return ResultUtils.success(result);
    }

    /**
     * 当前状态
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResult<User> getCurrentUser(HttpServletRequest request) {
        User currentUser = (User) request.getSession().getAttribute(BaseConst.USER_LOGIN_STATUS);
        if (currentUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN, "目前处于未登录状态！");
        }
        int userId = currentUser.getId();
        //TODO 校验用户是否合法
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }

    /**
     * 查询用户
     * @param username 用户昵称
     * @param request 请求
     * @return 用户信息
     */
    @GetMapping("/search")
    public BaseResult<List<User>> searchUsers(String username, HttpServletRequest request) {
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH, "无管理员权限！");
        }
        if (StringUtils.isNotBlank(username)) {
            List<User> list = userService.searchUsers(username);
            List<User> safetyUserist = list.stream().map(user -> {
                return userService.getSafetyUser(user);
            }).collect(Collectors.toList());
            return ResultUtils.success(safetyUserist);

        }
        throw new BusinessException(ErrorCode.NULL_ERROR, "查询用户名为空！");
    }

    /**
     * 删除用户
     * @param id 用户id
     * @param request 请求
     * @return 标志位
     */
    @PostMapping("/delete")
    public BaseResult<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH, "无管理员权限！");
        }
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "删除的id异常！");
        }

        boolean flag = userService.removeById(id);
        return ResultUtils.success(flag);
    }


    private boolean isAdmin(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute(BaseConst.USER_LOGIN_STATUS);
        if (user == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN, "目前处于未登录状态！");
        }
        return user.getUserRole() == BaseConst.ADMIN_USER;
    }

    private boolean isCommon(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute(BaseConst.USER_LOGIN_STATUS);
        if (user == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN, "目前处于未登录状态！");
        }
        return user.getUserRole() == BaseConst.COMMON_USER;
    }







}
